<template>
  <div class="warning-config-container">
    <page-header title="告警列表" icon="DataLine">
      <template #extra>
        <!-- Additional header content if needed -->
      </template>
    </page-header>
    <GapedColumn gap="large">
      <el-card style="width: 100%; border-radius: 4px">
        <template #header>
          <span class="card-header-title">告警历史曲线</span>
        </template>
        <LinesOfWarningLog
          :logs="apiStore.apiStates.getWarningLogs.data?.results || []"
          @point-click="handleLinePointClick"
        />
      </el-card>

      <el-card style="width: 100%; border-radius: 4px">
        <template #header>
          <span class="card-header-title">告警配置</span>
        </template>
        <GapedColumn>
          <el-button
            type="primary"
            style="width: auto"
            @click="handleAddConfig"
          >
            <el-icon><Plus /></el-icon>
            <span>配置</span>
          </el-button>
          <el-table :data="warningConfigs" style="width: 100%">
            <el-table-column prop="id" label="名称" />
            <el-table-column prop="tableName" label="表名称" />
            <el-table-column label="字段">
              <template #default="{ row }">
                <el-space wrap>
                  <el-tag v-for="field in row.dataFields" :key="field">{{
                    field
                  }}</el-tag>
                </el-space>
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-tag type="success">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template #default="{ row }">
                <el-button
                  type="primary"
                  size="small"
                  @click="handleEditConfig(row)"
                  >配置</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </GapedColumn>
      </el-card>
    </GapedColumn>

    <el-dialog
      v-model="showDialog"
      :title="currentConfig ? '编辑配置' : '新增配置'"
    >
      <WarningConfigCard
        v-if="showDialog"
        ref="warningCardRef"
        v-model="currentConfig"
        :tables="tables"
      />
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveConfig">保存</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="showLogDetailDialog" title="告警日志详情" width="70%">
      <WarningLogDetail
        v-if="showLogDetailDialog"
        :data="warningLogDetail.data"
        :query="warningLogDetail.query || ''"
        :total="warningLogDetail.total || 0"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import PageHeader from '@/components/layout/PageHeader.vue'
import { GapedColumn } from '@/core/components'
import useApi from '@/core/apiStore'
import { Plus } from '@element-plus/icons-vue'
import WarningConfigCard from '@/components/warning/WarningConfigCard.vue'
import LinesOfWarningLog from '@/components/warning/LinesOfWarningLog.vue'
import WarningLogDetail from '@/components/warning/WarningLogDetail.vue'
import { ElMessage } from 'element-plus'
import type { WarningConfig, Table } from '@/models/warning'

const apiStore = useApi()
const warningConfigs = computed<Array<WarningConfig>>(() => {
  const result = apiStore.apiStates.listWarningConfigs.data
  if (result) {
    return result.data || []
  }
  return []
})
const currentConfig = ref<WarningConfig | null>(null)
const showDialog = ref(false)
const warningCardRef = ref(null)

const showLogDetailDialog = ref(false)
const warningLogDetail = ref(null)

const tables = computed<Array<Table>>(() => {
  const { tables: data } = apiStore.apiStates.getTables.data || { table: [] }
  return data
})

const handleAddConfig = () => {
  currentConfig.value = { id: '', tableName: '', fields: [] } as WarningConfig
  showDialog.value = true
}

const handleEditConfig = (config: WarningConfig) => {
  currentConfig.value = { ...config }
  showDialog.value = true
}

const handleLinePointClick = async (id: string) => {
  const result = await apiStore.getWarningExectionLog({
    id,
    pageSize: 20,
    pageIndex: 0,
  })
  warningLogDetail.value = result || null
  console.log('log detail', result)
  showLogDetailDialog.value = true
}

const validateWarningConfig = (config: WarningConfig): boolean => {
  if (!config.id.trim()) {
    ElMessage.warning('配置名称不能为空')
    return false
  }
  if (!config.tableName.trim()) {
    ElMessage.warning('表名称不能为空')
    return false
  }
  if (config.conditionFields.length === 0) {
    ElMessage.warning('请至少添加一个条件字段')
    return false
  }
  if (config.dataFields.length === 0) {
    ElMessage.warning('请至少添加一个数据字段')
    return false
  }

  // 验证conditionFields中的字段
  for (const field of config.conditionFields) {
    if (!field.name.trim()) {
      ElMessage.warning('条件字段名称不能为空')
      return false
    }
    if (!field.field_type) {
      ElMessage.warning(`字段${field.name}的类型不能为空`)
      return false
    }
    if (
      field.value === undefined ||
      field.value === null ||
      field.value === ''
    ) {
      ElMessage.warning(`字段${field.name}的值不能为空`)
      return false
    }
    if (!field.operator) {
      ElMessage.warning(`字段${field.name}的操作符不能为空`)
      return false
    }
  }

  // 验证offsetIndexField
  if (!config.offsetIndexField?.name?.trim()) {
    ElMessage.warning('偏移索引字段名称不能为空')
    return false
  }
  if (
    config.offsetIndexField?.value === undefined ||
    config.offsetIndexField?.value === null ||
    config.offsetIndexField?.value === ''
    ) {
    ElMessage.warning('偏移索引字段值不能为空')
    return false
  }
  if (!config.offsetIndexField?.operator) {
    ElMessage.warning('偏移索引字段操作符不能为空')
    return false
  }

  if (!config.scanInterval || config.scanInterval <= 0) {
    ElMessage.warning('请设置有效的扫描间隔(必须大于0)')
    return false
  }

  return true
}

const handleSaveConfig = async () => {
  try {
    const newWarningConfig: WarningConfig =
      warningCardRef.value.getCurrentConfig()

    if (!validateWarningConfig(newWarningConfig)) {
      return
    }

    if (currentConfig.value.id) {
      await apiStore.createOrUpdateWarningConfig(newWarningConfig)
      ElMessage.success('保存成功')
    } else {
      await apiStore.createOrUpdateWarningConfig(newWarningConfig)
      ElMessage.success('新增成功')
    }
    showDialog.value = false
    await apiStore.listWarningConfigs()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

onMounted(async () => {
  try {
    await Promise.all([
      apiStore.getWarningLogs({ latest_days: 1 }),
      apiStore.getTables({}),
      apiStore.listWarningConfigs(),
    ])
  } catch (error) {
    ElMessage.error('初始化数据加载失败')
  }
})
</script>

<style scoped>
.warning-config-container {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header-title {
  font-size: 16px;
  font-weight: 500;
  color: var(--text-primary);
}
</style>